import axios from 'axios';
import { Local } from '@/store/cache';
//封装后端服务接口地址，同一个地址使用一个实例，不同地址使用不同实例（性能优化）
export const EleServerURL = { url: 'http://118.195.218.112:8080', server: null,uploadServer:null, EleServerUserTokenKey: 'EleServerUserToken' };
// 测试端口http://118.195.218.112:8080  正式端口http://111.231.5.158:8080
function getLocalToken(tokenKey) {
	let token = Local.get(tokenKey);
	if (!token) {
		token = '';
	}else{
		token='Bearer '+token;
	}
	return token;
}
const genernateServer=(is4UploadFile)=>{
	let server = axios.create({
		baseURL: EleServerURL.url,
		timeout: 2000
	});
	//请求拦截器，加入token，比如用于用户认证的token
	server.interceptors.request.use(
		request => {
			if (request.headers) {
				request.headers['Authorization'] = getLocalToken(EleServerURL.EleServerUserTokenKey);
				if(is4UploadFile==true){
					//request.headers['Content-Type'] = 'multipart/form-data;charset=UTF-8';
					request.headers['Content-Type'] = 'multipart/form-data;charset=UTF-8';
				}else{
					request.headers['Content-Type'] = 'application/json;charset=UTF-8';
				}
				return request;
			}
		},
		error => {
			return Promise.reject(error);
		}
	);
	return server;
}
export const ServerConfig = {
	getEleServer: () => {
		let server = EleServerURL.server;
		if (server == undefined || server == null) {
			server= genernateServer(false);
			EleServerURL.server = server;
		}
		return server;
	},
	getEleUploadServer: () => {
		let server = EleServerURL.uploadServer;
		if (server == undefined || server == null) {
			server= genernateServer(true);
			EleServerURL.uploadServer = server;
		}
		return server;
	},
	saveEleServerUserToken: token => {
		if (!token) {
			Local.remove(EleServerURL.EleServerUserTokenKey);
		} else {
			Local.set(EleServerURL.EleServerUserTokenKey, token);
		}
	}
};
